package com.example.testlxr9096.itemActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.testlxr9096.adapter.DetectItemAdapter;
import com.example.testlxr9096.adapter.GridSpacingItemDecoration;
import com.example.testlxr9096.adapter.IoAdapter;
import com.example.testlxr9096.bean.IoItem;
import com.example.testlxr9096.bean.Item;
import com.example.testlxr9096.ModbusClientManager;
import com.example.testlxr9096.ModbusTCPClient;
import com.example.testlxr9096.R;
import com.example.testlxr9096.adapter.SingleSelectAdapter;
import com.example.testlxr9096.bean.TitleItem;
import com.example.testlxr9096.adapter.TitleItemAdapter;
import com.example.testlxr9096.bean.KeyValuePair;
import com.example.testlxr9096.bean.TestRecord;
import com.example.testlxr9096.database.AppDatabase;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class WangXianTestActivity extends AppCompatActivity {

    private ModbusTCPClient modbusClient,modbusTCPClient2;

    private RecyclerView recyclerView,recyclerViewDecdect,rv_selcet,rv_title;
    private IoAdapter adapter;

    private Button bt_xun;
    private List<KeyValuePair> keyValuePairsList;

    private DetectItemAdapter detectItemAdapter;

    private SingleSelectAdapter singleSelectAdapter;
    private TitleItemAdapter titleItemAdapter;
    private List<IoItem> ioItems;
    private List<IoItem> dectectItems;
    private List<Item> itemList;
    private List<TitleItem> titleItems;
    private List<Integer> is_1_listPosition;

    private ScheduledExecutorService scheduler2,scheduler3;

    private int testPosition  = -1;

    private int[] values;
    int count;
    



    List<List<Integer>> listOfLists ;
    private  int itemPosition = 0 , clickNum  =0 ;
    private ModbusClientManager manager ;
    private TextView tv_selcetXianLang,tv_detectResult;
    private   Button btn_startDetect,btn_help,btn_back;
    private boolean isOnClick,isItemSelcet,isStart,isConnect,isStartDetect,isopen;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wangxian);


        initData();
        initView();
        initRecycleView();
        initDectRecycleView();

        initBottonButtons();

    }
    private void initBottonButtons() {
        // 通过 include 的 id 获取按钮
        View includeView = findViewById(R.id.include_buttons);
        btn_help = includeView.findViewById(R.id.btn_help);
        btn_back = includeView.findViewById(R.id.btn_back);

        btn_help.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(WangXianTestActivity.this, Help.class);
                int numberToSend = 1; // 要传递的数字
                intent.putExtra("key_number", numberToSend);
                startActivity(intent);
            }
        });
        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });


    }
    private void initData() {
        manager = ModbusClientManager.getInstance();
        modbusClient = manager.getDevice1();
        modbusTCPClient2 = manager.getDevice2();
        ioItems = new ArrayList<>();
        is_1_listPosition = new ArrayList<>();
        itemList = new ArrayList<>();
        titleItems = new ArrayList<>();
        listOfLists = new ArrayList<>(4);
        itemList.clear();

        dectectItems = new ArrayList<>();
        keyValuePairsList = new ArrayList<>();




        for (int i =0;i<8;i++){
            itemList.add(new Item("待测",String.valueOf(i),0,0,false));
            titleItems.add(new TitleItem(String.valueOf(i+1)));
            dectectItems.add(new IoItem(String.valueOf(i+1)));
            ioItems.add(new IoItem(String.valueOf(i+1)));

            keyValuePairsList.add(new KeyValuePair("Q0."+i+2,35+i,0));

        }
//        ioItems.add(new IoItem("E"));
//        ioItems.add(new IoItem("F"));


    }

    public void clearArray(){

        is_1_listPosition.clear();
        listOfLists.clear();




    }

    public void initView() {

        tv_detectResult = findViewById(R.id.tv_result);

        bt_xun = findViewById(R.id.bt_xun);


        btn_startDetect = findViewById(R.id.btn_startDetect);

        bt_xun.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                ioItems.get(8).setSelected(true);
//                ioItems.get(9).setSelected(true);

//                adapter.notifyDataSetChanged();
                clickNum = 49152;

            }
        });



        btn_startDetect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isopen) {
                    btn_startDetect.setText("开始检测");
                    isStartDetect = false;
                    isopen = false;
                    stopTest();

                } else {
                    btn_startDetect.setText("停止检测");
                    isStartDetect = true;
                    startDecdect();
                    clickNum = 0;
                    isopen = true;

                }

            }
        });

    }

    public  void stopTest(){
        modbusClient.writeMultipleRegisters(1, 32, new int[]{ 0, 0});
        itemPosition = 0;
        for (int i = 0;i<8;i++){
            IoItem item2= ioItems.get(i);

            item2.setSelected(false);
        }
        for (int i = 0;i<dectectItems.size();i++){

            dectectItems.get(i).setState(0);
        }
        adapter.notifyDataSetChanged();
        detectItemAdapter.notifyDataSetChanged();


    }


    public void setXianState(int position,int state,String error){
        itemList.get(position).setStatus(state);

        if (position<7){
            if (position>=1){
                dectectItems.get(position-1).setState(0);
            }

        }else {

        }

        dectectItems.get(position).setState(state);
        if (state==1){
            itemList.get(position).setTitle("PASS");
            if (itemList.get(position).getLastStatus()!=itemList.get(position).getStatus()){
                itemList.get(position).setLastStatus(itemList.get(position).getStatus());
                saveTestResult("网线检测",itemList.get(position).getTitle0(),"","通过");

            }

        }else if (state==2){
            itemList.get(position).setTitle("NG");
            if (itemList.get(position).getLastStatus()!=itemList.get(position).getStatus()){
                itemList.get(position).setLastStatus(itemList.get(position).getStatus());
                saveTestResult("网线检测",itemList.get(position).getTitle0(),error,"不通过");

            }
//            AlarmHelper.playBeepAlarm(WangXianTestActivity.this);


        }else {
            itemList.get(position).setTitle("待测");
        }




    }
    public void  initRecycleView(){
        recyclerView = findViewById(R.id.recycler_view);
        GridLayoutManager layoutManager = new GridLayoutManager(this, 8);
        recyclerView.setLayoutManager(layoutManager);
        // 添加间距装饰器
        int spacing = getResources().getDimensionPixelSize(R.dimen.grid_spacing);
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(8, spacing, true));
        adapter = new IoAdapter(ioItems);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(position -> {

//            isStart = true;
//
//            isOnClick = true;
//
//            // 切换选中状态
//            IoItem item = ioItems.get(position);
//            isItemSelcet = item.isSelected();
//
//            item.setSelected(!item.isSelected());
//
//
//            // 通知适配器该项已更改
            adapter.notifyItemChanged(position);

        });

    }

    public void  initDectRecycleView(){
        recyclerViewDecdect = findViewById(R.id.recyclerLong_view);
        GridLayoutManager layoutManager = new GridLayoutManager(this, 8);
        recyclerViewDecdect.setLayoutManager(layoutManager);

        // 添加间距装饰器
        int spacing = getResources().getDimensionPixelSize(R.dimen.grid_spacing);
        recyclerViewDecdect.addItemDecoration(new GridSpacingItemDecoration(8, spacing, true));
        detectItemAdapter = new DetectItemAdapter(dectectItems);
        recyclerViewDecdect.setAdapter(detectItemAdapter);
        detectItemAdapter.setOnItemClickListener(position -> {

            IoItem item = dectectItems.get(position);
            isItemSelcet = item.isSelected();

            item.setSelected(!item.isSelected());
            detectItemAdapter.notifyItemChanged(position);

        });

    }
    public void  initXianRecycleView(){
        rv_title = findViewById(R.id.rv_title);

        rv_selcet = findViewById(R.id.rv_selcet);
        GridLayoutManager layoutManager = new GridLayoutManager(this, 8);
        GridLayoutManager layoutManager1 = new GridLayoutManager(this, 8);
        layoutManager.setSpanCount(8);
        layoutManager1.setSpanCount(8);

        rv_selcet.setLayoutManager(layoutManager);
        rv_title.setLayoutManager(layoutManager1);

        // 添加间距装饰器
        int spacing = getResources().getDimensionPixelSize(R.dimen.grid_spacing);
        rv_selcet.addItemDecoration(new GridSpacingItemDecoration(8, spacing, true));
        rv_title.addItemDecoration(new GridSpacingItemDecoration(8, spacing, true));

        titleItemAdapter = new TitleItemAdapter(titleItems);
        singleSelectAdapter = new SingleSelectAdapter(itemList);
        rv_selcet.setAdapter(singleSelectAdapter);
        rv_title.setAdapter(titleItemAdapter);
        singleSelectAdapter.setOnItemClickListener(position -> {
            testPosition = position;
        });



    }
    @Override
    protected void onDestroy() {

        isStart =false;
        isStartDetect = false;
        if (scheduler2!=null){
            scheduler2.shutdown();
        }
        if (scheduler3!=null){
            scheduler3.shutdown();
        }
        super.onDestroy();



    }
    public void saveTestResult(String type, String name, String errorInfo, String state) {
        TestRecord testRecord = new TestRecord();
        testRecord.setDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        testRecord.setType(type);
        testRecord.setName(name);
        testRecord.setErrorInfo(errorInfo);
        testRecord.setState(state);
        Log.d("insert", "saveTestResul[[[[[[[[[ ");

        AppDatabase.getDatabase(WangXianTestActivity.this).testRecordDao().insert(testRecord);
    }

    @Override
    protected void onPause() {

        isStart =false;
        isStartDetect = false;
        if (scheduler2!=null){
            scheduler2.shutdown();
        }
        if (scheduler3!=null){
            scheduler3.shutdown();
        }
        super.onPause();
    }

    @Override
    protected void onStop() {

        isStart =false;
        isStartDetect = false;
        if (scheduler2!=null){
            scheduler2.shutdown();
        }
        if (scheduler3!=null){
            scheduler3.shutdown();
        }
        super.onStop();



    }
    public void startDecdect(){
        isStart = true;

         scheduler2 = Executors.newSingleThreadScheduledExecutor();
         initThread();

         readTask();


    }
    public void writeTask(){



    }


    public void readTask(){
        is_1_listPosition.clear();
        Runnable task2 = () -> {

            while (isStartDetect){
                //接收数据
                values = modbusTCPClient2.readHoldingRegisters(1, 4, 4);


//
//
                if (values != null) {
                    clearArray();
                    int bitLength = 0;


                    for (int i= 0;i<values.length ;i++) {
                        // 转换为二进制字符串（自动去掉前导零）
                        String binary = Integer.toBinaryString(values[i]);
                        bitLength = binary.length(); // 有效位长度

                        // 存储"1"的位置（从最低位开始计数，0表示最低位）


                        // 从最低位（字符串末尾）向最高位遍历
                        for (int j = binary.length() - 1; j >= 0; j--) {
                            if (binary.charAt(j) == '1') {
                                // 计算位位置：字符串索引i对应的位位置 = (bitLength - 1 - i)
                                int bitPosition = bitLength - 1 - j;
                                switch (i){
                                    case 0:
                                        is_1_listPosition.add(bitPosition);
                                        break;
                                    case 1:
                                        is_1_listPosition.add(bitPosition+16);
                                        break;
                                    case 2:
                                        is_1_listPosition.add(bitPosition+32);
                                        break;
                                    case 3:
                                        is_1_listPosition.add(bitPosition+48);
                                        break;


                                }



                            }

                        }

                    }

//
//                    for (int i = 0;i<itemList.size();i++){
//                        setXianState(i,0);
//                    }
////                    //设置位置
                    for (int i = 0;i<is_1_listPosition.size();i++){
                        Log.d("readTask", "readTask:is_1_listPosition  "+itemPosition);

                        if (is_1_listPosition.contains(keyValuePairsList.get(itemPosition).getHuang()-1)){
                            setXianState(itemPosition,1,"");


                        }else {
                            setXianState(itemPosition,2,"");

                        }

                    }



                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            detectItemAdapter.notifyDataSetChanged();


                        }
                    });


                } else {
//
                }

            }





        };

        scheduler2.scheduleAtFixedRate(task2, 0, 100, TimeUnit.MILLISECONDS);

    }
    public void initThread(){
        count = 0;
         scheduler3 = Executors.newSingleThreadScheduledExecutor();


        // 2. 定义任务内容
        Runnable task3 = () -> {
            if (modbusClient != null) {
                if (isStartDetect) {
                count++;
                double result = 0;
                result = Math.pow(2, itemPosition + 2);
                if (!(clickNum ==1020)){

                clickNum = (int) result;
                }

                    if (count == 10) {
                        itemPosition += 1;

                        count = 0;
                    }
                    if (itemPosition + 1 > 8) {

                        clickNum =1020 ;
                        itemPosition =7;




                    }

                    Log.d("lccc", "clicknum: " + clickNum);





                if (clickNum < 65535) {


                    modbusClient.writeMultipleRegisters(1, 32, new int[]{(int) clickNum, 0});

                } else {

                    modbusClient.writeMultipleRegisters(1, 32, new int[]{65535, (int) clickNum - 65535});
                }




                if (itemPosition+1>7){

                    for (int i = 0;i<8;i++){
                        IoItem item2= ioItems.get(i);

                        item2.setSelected(true);
                    }

                    }else {
                    IoItem item = ioItems.get(itemPosition);
                    isItemSelcet = item.isSelected();
                    item.setSelected(true);
//
                    if (itemPosition>0){

                        IoItem item1 = ioItems.get(itemPosition-1);
                        item1.setSelected(false);

                    }



                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter.notifyDataSetChanged();
                    }
                });


                // 通知适配器该项已更改

            }
            }

        };

        scheduler3.scheduleAtFixedRate(task3, 0, 100, TimeUnit.MILLISECONDS);

    }







}